package com.sunlee.app.api.interceptor;

import com.sunlee.app.api.annotation.Login;
import com.sunlee.app.api.entity.TokenEntity;
import com.sunlee.app.api.service.TokenService;
import com.sunlee.app.api.service.UserService;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.entity.CommonUserEntity;
import com.sunlee.common.service.enums.StatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：权限(Token)验证
 *
 * @author sunlee
 */
@Component
public class AuthorizationInterceptor implements AsyncHandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    public static final String USER_KEY = "userId";

    public static final String USER_INFO_KEY = "userInfo";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }

        //token为空
        if (StringUtils.isBlank(token)) {
            if (!annotation.required()) {
                return true;
            }
            throw new BusinessException(ErrorCodeEnum.UNAUTHORIZED);
        }

        //查询token信息
        TokenEntity tokenEntity = tokenService.getByToken(token);
        if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
            if (!annotation.required()) {
                return true;
            }
            throw new BusinessException(ErrorCodeEnum.TOKEN_INVALID);
        }

        //获取用户信息
        CommonUserEntity userInfo = userService.getUserByUserId(tokenEntity.getUserId());

        // 黑名单账号
        if (StatusEnum.INVALID.getCode() == userInfo.getStatus()) {
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_DISABLED);
        }

        //设置userId到request
        request.setAttribute(USER_KEY, tokenEntity.getUserId());
        request.setAttribute(USER_INFO_KEY, userInfo);

        return true;
    }
}
